package com.project.service.impl;

import com.project.common.*;
import com.project.dao.UserMapper;
import com.project.dao.UserRoleMapper;
import com.project.pojo.User;
import com.project.pojo.UserRole;
import com.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Service("userServerImpl")
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisCacheManager redisCache;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public ServerResponse<User> checkLogin(String username, String password) {
        if (StringUtils.isBlank(username))
            return ServerResponse.createByErrorMessage("账号为空!");
        if (StringUtils.isBlank(password))
            return ServerResponse.createByErrorMessage("密码为空!");
        User currentUser = userMapper.selectByUserName(username);
        if(currentUser == null || currentUser.getUsername() == null){
            return ServerResponse.createByErrorMessage("账号或密码有误!");
        }
        if (!MD5Utils.checkPassword(password, currentUser.getPassword())) {
            return ServerResponse.createByErrorMessage("密码错误!");
        }
        currentUser.setPassword(null);
        currentUser.setToken(System.currentTimeMillis() + "");
        //todo 未整合shiro
        UserRole userRole = userRoleMapper.selectByPrimaryKey(currentUser.getId());
        currentUser.setRole(userRole.getRoleId());
        return ServerResponse.createBySuccess("登录成功!", currentUser);
    }

    @Override
    @Transactional
    public ServerResponse<String> createUser(User user) {

        if((StringUtils.isBlank(user.getUsername())||StringUtils.isBlank(user.getPassword())||StringUtils.isBlank(user.getRealName())
        ||StringUtils.isBlank(user.getGrade())||StringUtils.isBlank(user.getAddress())||StringUtils.isBlank(user.getSex()))){

            return ServerResponse.createByErrorMessage("请填写必填项!!");
        }
        //todo 可以再次校验用户信息  这里只校验用户名是否已存在
        ServerResponse<String> serverResponse = checkUser(user.getUsername());
        if (serverResponse.getStatus() != 0) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.USERNAME_EXIST.getCode(), "此学号已注册,如忘记密码请联系管理员!");
        }

        try {
            user.setPassword(MD5Utils.encryptPassword(user.getPassword()));
        } catch (Exception e) {
            log.error("注册失败,注册异常!");
            return ServerResponse.createBySuccess("注册失败!");
        }
        int i;
        try {
            i = userMapper.insertSelective(user);
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(user.getRole());
            userRoleMapper.insertSelective(userRole);
        }catch (Exception e){
            throw  e;
        }

        if (i != 1) {
            return ServerResponse.createBySuccess("注册失败!");
        }
        return ServerResponse.createBySuccess("注册成功!");
    }

    @Override
    public ServerResponse<String> checkUser(String username) {
        User user1 = userMapper.selectByUserName(username);
        if (user1 != null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.USERNAME_EXIST.getCode(), "用户已存在!");
        }
        return ServerResponse.createBySuccessMessage("验证成功!");
    }

    @Override
    public ServerResponse<User> updateUserInfo(User user) {
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i < 1) {
            return ServerResponse.createByErrorMessage("修改个人信息失败!");
        }
        if (!redisCache.cacheUserInfo(userMapper.selectByPrimaryKey(user.getId()))) {
            return ServerResponse.createByErrorMessage("修改个人信息失败!");
        }
        return ServerResponse.createBySuccessMessage("修改成功!");
    }

    @Override
    public ServerResponse logout(String token) {
        if (!redisCache.delKey("username." + token)) {
            ServerResponse.createByErrorMessage("退出失败!");
        }
        return ServerResponse.createBySuccess("退出系统成功!");
    }

    @Override
    public User findUserByUserName(String username) {
        User user = null;
        try {
            user = userMapper.selectByUserName(username);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return user;
    }

    /**
     * @param file
     * @param userId
     */
    @Override
    public ServerResponse<String> uploadHeadImg(File file, Integer userId) {
        try {
            //获取user  得到原来的头像地址
            User user = userMapper.selectByPrimaryKey(userId);
            //调用七牛
            String imgUrlName = QiniuFileUploadUtil.uploadHeadImg(file);
            user.setHeadImage(imgUrlName);
            //更新用户头像URL
            userMapper.updateByPrimaryKeySelective(user);
            return ServerResponse.createBySuccess("修改头像成功!", Const.QINIU_HEAD_IMG_BUCKET_URL + "/" + imgUrlName);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return ServerResponse.createByErrorMessage("修改头像失败!");
    }

    @Override
    public List<User> myAllStudent(User currentUser) {
        List<User> list = userMapper.selectMyAllUser(currentUser.getId(),currentUser.getGrade());
        List<User> list1 = new ArrayList<>();
        for(User user : list){
            user.setPassword("");
            list1.add(user);
        }
        return list1;
    }

    @Override
    @Transactional
    public int deleteUserById(int id) {
        try {
            if(userMapper.deleteByPrimaryKey(id) == userRoleMapper.deleteByPrimaryKey(id)){
                return 1;
            }
        }catch (Exception e){
            //抛异常则事务回滚
            throw e;
        }
        return 0;
    }

    @Override
    public int updateStuInfo(User user) {
        int i = userMapper.updateByPrimaryKeySelective(user);
        return i;
    }
}
